﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;

namespace MoveNext.GrfFileManager
{
    public class SortableBindingList<T> : BindingList<T>
    {
        private bool isSorted;
        private PropertyDescriptor lastProperty;
        private ListSortDirection lastDirection;

        protected override bool SupportsSortingCore
        {
            get { return true; }
        }

        protected override void ApplySortCore(PropertyDescriptor property, ListSortDirection direction)
        {
            // Get list to sort
            List<T> items = (List<T>)this.Items;

            if (this.lastProperty != null && this.lastProperty.Equals(property))
            {
                direction = this.lastDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
            }
            this.lastProperty = property;
            this.lastDirection = direction;

            // Apply and set the sort, if items to sort
            PropertyComparer<T> pc = new PropertyComparer<T>(property, direction);
            items.Sort(pc);
            this.isSorted = true;

            // Let bound controls know they should refresh their views
            this.OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
        }

        protected override bool IsSortedCore
        {
            get { return isSorted; }
        }

        protected override void RemoveSortCore()
        {
            this.isSorted = false;
        }
    }
}
